package com.xiaoshuidi.cloud.module.rooms.job.xxljob;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.iot.api.device.DeviceApi;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.PullDeviceApiVo;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.RoomHouseUtil;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomHouseMapper;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomHouse;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotDeviceMapping;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotWaring;
import com.xiaoshuidi.cloud.module.rooms.repository.IotWaringRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomSdiotDeviceMappingRepository;
import com.xiaoshuidi.cloud.module.system.api.sms.SmsSendApi;
import com.xiaoshuidi.cloud.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import com.xiaoshuidi.cloud.module.system.api.user.dto.AdminUserRespDTO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房源预警信息
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SmartDeviceWarningJob {
    @Autowired
    private IotWaringRepository iotWaringRepository;
    @Autowired
    private DeviceApi deviceApi;
    @Autowired
    private RoomSdiotDeviceMappingRepository roomSdiotDeviceMappingRepository;
    @Autowired
    private RoomHouseMapper roomHouseMapper;
    @Autowired
    private SmsSendApi smsSendApi;
    @Autowired
    private AdminUserApi adminUserApi;

    @XxlJob("smartDeviceWarningJob")
    @TenantIgnore
    public void smartDeviceWarningJob() {
        log.info("************************smartDeviceWarningJob start******************************");
        List<RoomSdiotWaring> list=iotWaringRepository.list();
        //查询状态
        list.forEach(item->{
            //未出租连续开门
            if(item.getNotLetContinuousOpenDoor() == 1 && item.getNotLetContinuousOpenDoorDay() != null){
                Integer notLetContinuousOpenDoorDay = item.getNotLetContinuousOpenDoorDay();
                String format = DateUtil.format(DateUtil.offsetDay(new Date(), -notLetContinuousOpenDoorDay), "yyyy-MM-dd");
                ResultModel<List<PullDeviceApiVo>> resultModel = deviceApi.queryOpenDoor(format);
                List<PullDeviceApiVo> data = resultModel.getData();
                if (CollectionUtil.isNotEmpty(data)) {
                    data.forEach(itemDoorLock -> {
                        //超过时间
                        if (itemDoorLock.getOnlineStatus() >= notLetContinuousOpenDoorDay) {
                            RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                            RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                            if (!roomHouse.getGrounding())
                                smsSend(roomHouse,"房屋未出租连续开门预警");//发送短信
                        }
                    });
                }
            }

            if(item.getRentOutNoOpenDoor() == 1){
                //出租连续 无开门记录
                if(item.getRentOutNoOpenDoorDay() != null) {
                    Integer rentOutNoOpenDoorDay = item.getRentOutNoOpenDoorDay();
                    String format = DateUtil.format(DateUtil.offsetDay(new Date(), -rentOutNoOpenDoorDay), "yyyy-MM-dd");
                    ResultModel<List<PullDeviceApiVo>> resultModel = deviceApi.queryNotOpenDoor(format);
                    List<PullDeviceApiVo> data = resultModel.getData();
                    if (CollectionUtil.isNotEmpty(data)) {
                        data.forEach(itemDoorLock -> {
                            RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                            RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                            if (!roomHouse.getGrounding())
                                smsSend(roomHouse,"门锁离线或断电");//发送短信
                        });
                    }
                }
                //单日开门超过次数
                if(item.getSingleDayOpeningNum() != null){
                    Integer singleDayOpeningNum = item.getSingleDayOpeningNum();

                    ResultModel<List<PullDeviceApiVo>> resultModel = deviceApi.queryOpenNum(DateUtil.format(DateUtil.yesterday(),"yyyy-MM-dd"));
                    List<PullDeviceApiVo> data = resultModel.getData();
                    if (CollectionUtil.isNotEmpty(data)) {
                        data.forEach(itemDoorLock -> {
                            if(singleDayOpeningNum<itemDoorLock.getOnlineStatus()){
                                RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                                RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                                if (!roomHouse.getGrounding())
                                    smsSend(roomHouse,"门锁离线或断电");//发送短信
                            }
                        });
                    }
                }
            }
            //门锁异常预警
            if(item.getDoorLockOffline() == 1 && item.getDoorLockOfflineDay() != null){
                Integer doorLockOfflineDay = item.getDoorLockOfflineDay();
                String format = DateUtil.format(DateUtil.offsetDay(new Date(), -doorLockOfflineDay), "yyyy-MM-dd HH:mm:ss");
                ResultModel<List<PullDeviceApiVo>> resultModel = deviceApi.queryDeviceState("doorlock",format);
                List<PullDeviceApiVo> data = resultModel.getData();
                if(CollectionUtil.isNotEmpty(data)){
                    data.forEach(itemDoorLock->{
                        RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                        RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                        //发送短信
                        smsSend(roomHouse,"门锁离线或断电");
                    });

                }
            }

            //电表异常预警
            if(item.getEnergyMeterOffline() == 1 && item.getEnergyMeterOfflineDay() != null){
                Integer doorLockOfflineDay = item.getDoorLockOfflineDay();
                String format = DateUtil.format(DateUtil.offsetDay(new Date(), -doorLockOfflineDay), "yyyy-MM-dd HH:mm:ss");
                ResultModel<List<PullDeviceApiVo>> resultModel = deviceApi.queryDeviceState("ammeter",format);
                List<PullDeviceApiVo> data = resultModel.getData();
                if(CollectionUtil.isNotEmpty(data)){
                    data.forEach(itemDoorLock->{
                        RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                        RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                        //发送短信
                        smsSend(roomHouse,"电表离线或断电");
                    });
                }
            }

            //水表异常预警
            if(item.getWaterMeterOffline() == 1 && item.getWaterMeterOfflineDay() != null){
                Integer doorLockOfflineDay = item.getDoorLockOfflineDay();
                String format = DateUtil.format(DateUtil.offsetDay(new Date(), -doorLockOfflineDay), "yyyy-MM-dd HH:mm:ss");
                ResultModel<List<PullDeviceApiVo>> coldResultModel = deviceApi.queryDeviceState("cold_watermeter",format);
                ResultModel<List<PullDeviceApiVo>> hotResultModel = deviceApi.queryDeviceState("hot_watermeter",format);
                List<PullDeviceApiVo> cold = coldResultModel.getData();
                List<PullDeviceApiVo> hot = hotResultModel.getData();
                cold.addAll(hot);
                if(CollectionUtil.isNotEmpty(cold)){
                    cold.forEach(itemDoorLock->{
                        RoomSdiotDeviceMapping byDeviceNo = roomSdiotDeviceMappingRepository.getByDeviceNo(itemDoorLock.getDeviceNo());
                        RoomHouse roomHouse = roomHouseMapper.selectById(byDeviceNo.getRoomHouseId());
                        //发送短信
                        smsSend(roomHouse,"热/冷水表离线或断电");
                    });
                }
            }
        });
    }

    private void smsSend(RoomHouse roomHouse,String incident){
        AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(roomHouse.getUpdater())).getData();
        String houseFullName = RoomHouseUtil.getHouseFullName(roomHouse);
        Map<String, Object> map =  new HashMap<>();
        // 获得渠道对应的 SmsClient 客户端
        SmsSendSingleToUserReqDTO smsSendSingleToUserReqDTO = new SmsSendSingleToUserReqDTO();
        map.put("roomFullName",houseFullName);
        map.put("incident",incident);
        //短信渠道
        smsSendSingleToUserReqDTO.setTemplateCode("reserve_ticket_reminders");

        smsSendSingleToUserReqDTO.setMobile(user.getMobile());
        smsSendSingleToUserReqDTO.setUserId(user.getId());
        smsSendSingleToUserReqDTO.setTemplateParams(map);
        smsSendApi.sendSingleSmsToMember(smsSendSingleToUserReqDTO);

    }
}
